/*
* 车间管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken} = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 获取车间列表
router.get("/list", async (req, res) => {
    console.log("===========获取车间列表接口============");
    // 获取参数
    let { pageNum, pageSize, workshopCode, workshopName } = req.query;
    // 拼接sql语句
    let sql = "select * from md_workshop";
    let sql_where = ` where 1=1`;
    if(workshopCode){
        sql_where += ` and workshop_code like '%${workshopCode}%'`;
    }
    if(workshopName){
        sql_where += ` and workshop_name like '%${workshopName}%'`;
    }
    if(workshopCode || workshopName ){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询车间列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询车间列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询车间总数", `select count(*) as count from md_workshop ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询车间总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询车间列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询车间列表成功", rows: [], total: 0});
            }
        })
    })
})

// 添加车间
router.post("/", async (req, res) => {
    console.log("===========添加车间接口============");
    // 获取参数
    let { workshopCode, workshopName, area, charge, enableFlag, remark } = req.body;
     // 获取创建人
     let {username} = verifyToken(req.headers.authorization);
     // 获取创建时间
     let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
     // 判断车间编码和车间名称是否重复
     db.query("查询车间编码是否重复", `select * from md_workshop where workshop_code='${workshopCode}' or workshop_name = '${workshopName}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询车间编码是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "车间编码或车间名称已存在", data: []});
            return;
        }
        // 插入数据库
        let sql = `insert into md_workshop (workshop_code, workshop_name, area, charge, enable_flag, remark, create_by, create_time) 
        values('${workshopCode}', '${workshopName}', '${area}', ${charge ? "'"+charge+"'" : null}, '${enableFlag}', ${remark ? "'"+remark+"'" : null}, '${username}', '${createTime}')`;
        db.query("添加车间", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "添加车间失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "添加车间成功", data: []});
            }else{
                res.send({code: 500, msg: "添加车间失败", data: []});
            }
        })
     })
})

// 查询单个车间
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个车间接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个车间", `select * from md_workshop where workshop_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个车间失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个车间成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个车间失败"});
        }
    })
})

// 修改车间
router.put("/", (req, res)=>{
    console.log("===========修改车间接口============");
    // 获取参数
    let { workshopId, workshopCode, workshopName, area, charge, enableFlag, remark } = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询车间名称是否重复
    db.query("查询车间名称是否重复", `select * from md_workshop where workshop_id != ${workshopId} and (workshop_code='${workshopCode}' or workshop_name = '${workshopName}')`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询车间名称是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "车间编码或车间名称已存在", data: []});
            return;
        }
        // 修改车间sql
        let sql = `update md_workshop set workshop_code='${workshopCode}', workshop_name='${workshopName}', area='${area}', 
        charge=${charge ? "'"+charge+"'" : null}, enable_flag='${enableFlag}', remark=${remark ? "'"+remark+"'" : null}, update_by='${username}', 
        update_time='${updateTime}' where workshop_id = ${workshopId}`;
        db.query("修改车间", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改车间失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改车间成功", data: []});
            }else{
                res.send({code: 500, msg: "修改车间失败", data: []});
            }
        })
    })
})

// 删除车间
router.delete("/:id", (req, res) => {
    console.log("===========删除车间接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from md_workshop where workshop_id in(${id})`;
    // 查询数据库
    db.query("删除车间", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除车间失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除车间成功"})
        }else{
            res.send({code: 500, msg: "删除车间失败"})
        }
    })
})

// 查询所有有效车间
router.get("/listAll", (req, res) => {
    console.log("===========查询所有有效车间接口============");

    let sql = `select * from md_workshop where enable_flag = 'Y'`;
    // 查询数据库
    db.query("查询所有有效车间", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "查询所有有效车间失败", data: err});
            return
        }
        if (result.length > 0) {
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
               return toCamelCase(item)
           })
       }
       res.send({code: 200, msg: "查询所有有效车间成功", data: result})
    })
})

module.exports = router;
